﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text;

namespace Bon_It.Model
{
    /// <summary>
    /// The 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [DataContract]
    public class EntityBase<T> : IEntityBase, IDataErrorInfo
    {

        protected void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
        }
    

        private EntityBase<T> _backup;

        public void BeginEdit()
        {
            _backup = (EntityBase<T>) Clone();
        }

        public void EndEdit()
        {
            _backup = null;
        }

        public void CancelEdit()
        {
           
            Debug.Assert(_backup != null, "The BeginEdit method wouldn't be called");
            foreach (var theItem in GetType().GetProperties())
            {
                // exclude the changed property
                if (string.Equals(theItem.Name,"IsChanged",StringComparison.InvariantCultureIgnoreCase))
                {
                    continue;
                }

                object value = _backup.GetType().GetProperty(theItem.Name).GetValue(_backup, null);
                GetType().GetProperty(theItem.Name).SetValue(this,value,null);   
            }

        }

        /// <summary>
        /// Create a cloned object.
        /// </summary>
        /// <returns></returns>
        public object Clone()
        {
            return this.MemberwiseClone();
        }

        public virtual string this[string columnName]
        {
            // default implementation
            get {
                switch (columnName)
                {
                    default:
                        return "";
                }
            }
        }

        /// <summary>
        /// Gets the errorstrings.
        /// </summary>
        public virtual string Error
        {
            get { return string.Empty; }
        }
    }
}
